#!/usr/bin/env python
import os
import urllib
import datetime
import urlparse
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
#use_library('django', '1.2')
from google.appengine.api import images
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson as json
from google.appengine.ext.webapp import util

import DataModels
class FileExplorer(webapp.RequestHandler):
    def get(self,file_key=None):
        u = DataModels.DataUser.get_current_user()
        f = DataModels.File.all().ancestor(u).filter('__key__', db.Key(file_key)).fetch(1)[0]
        template_values = { 'page_title' : 'File ' + f.name,
                               'user_nickname' : u.user.nickname(),
                               'file' : f,
                               'mp3_url': '/FileExplorer/Download/' + file_key
                               }
            
        if(f.blob_info.content_type == 'audio/mp3'):
            path = os.path.join(os.path.dirname(__file__), 'templates/FileExplorerMp3.html')
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect('/FileExplorer/Download/' + file_key)
            
class FileExplorerDownload(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, file_key):
        u = DataModels.DataUser.get_current_user()
        f = DataModels.File.all().ancestor(u).filter('__key__', db.Key(file_key)).fetch(1)[0]
        self.response.headers.add_header('Content-Disposition','attachment;filename=' + f.blob_info.filename)
        self.send_blob(f.blob_info)

def main():
    application = webapp.WSGIApplication([
                                            ('/FileExplorer/Download/([^/]+)?', FileExplorerDownload),
                                            ('/FileExplorer/([^/]+)?', FileExplorer)
                                         ],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
